<template>
  <fks-dialog
    :visible="true"
    width="480px"
    @close="cancel"
  >
    <div slot="title">
      <i class="fks-icon-edit" />
      {{ LANG.CHANGE_USERNAME }}
    </div>
    <fks-form
      ref="form"
      :model="form"
      label-position="left"
      label-width="70px"
      :rules="rules"
    >
      <fks-form-item
        :label="LANG.USERNAME"
        class="form-group"
        prop="userName"
      >
        <fks-input
          v-model="form.userName"
          maxlength="11"
          show-word-limit
        />
      </fks-form-item>
    </fks-form>
    <div slot="footer">
      <fks-button
        type="primary"
        icon="fks-icon-check"
        :loading="submitLoading"
        @click="submit"
      >
        {{ LANG.SAVE }}
      </fks-button>
    </div>
  </fks-dialog>
</template>
<script>
import { updataPhone } from '../api'
export default {
  name: 'ChangePhone',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: {},
      submitLoading: false
    }
  },
  computed: {
    rules() {
      return {
        userName: [
          {
            required: true,
            message: this.LANG.USERNAME_NOT_EMPTY,
            trigger: 'blur'
          },

          {
            pattern: /^[a-z][a-z0-9_]*$/g,
            message: this.LANG.FORMAT_ERROR
          }
        ]
      }
    },
    user() {
      return this.$store.state.user
    }
  },
  methods: {
    cancel() {
      this.$emit('update:visible', false)
    },
    submit() {
      this.submitLoading = true
      this.$refs.form.validate((valid) => {
        if (valid) {
          updataPhone({
            userName: this.form.userName,
            id: this.user.id
          })
            .then((res) => {
              if (res.status) {
                this.$message.success(this.LANG.EDIT_SUCCESS)
                this.$store.dispatch('updateUser')
                this.$parent.updatePhone(this.form.userName)
                this.cancel()
              }
              this.submitLoading = false
            })
            .catch((err) => {
              this.submitLoading = false
            })
        } else {
          this.submitLoading = false
        }
      })
    }
  }
}
</script>
<style>
</style>